import os

import ddddocr
import base64
import sys
import requests,jsonpath

print("Python version")
print(sys.version)



def get_captcha():
    payload = {
        "method":"get",
        "url": os.environ["URL"] + "/auth/captcha"
    }
    response = requests.request(**payload)

    sn = jsonpath.jsonpath(response.json(),"$..sn")[0]
    image = jsonpath.jsonpath(response.json(),"$..image")[0]
    return sn,image

def dddd_ocr_text(image):
    #步骤1.需要对image进行分割，得到头部和Base64编码的部分
    encode_data = image.split(",")[1]
    # print(encode_data)

    #步骤2：解码Base64源数据
    decode_data = base64.b64decode(encode_data)
    # print(decode_data)


    #步骤3：通过ddddocr来识别图片源数据
    ocr = ddddocr.DdddOcr()
    text = ocr.classification(decode_data)
    return text

# 存放全局的验证码文本和sn文本
sn_captcha_text = {}

# 执行次数、
run_nums = 0

def get_res_sn_captcha():
    #获取验证码和sn的最终方法
    global run_nums
    #如果是生产环境，按照下面的逻辑走，先请求数据，再调用ocr识别
    if os.environ["ENV"] == "pord":
        #判断第一次执行的时候和失败重试的时候才会执行下面的获取验证码和sn的逻辑
        if not sn_captcha_text or run_nums % 2 == 0:
            sn, image = get_captcha()
            captcha = dddd_ocr_text(image)
            sn_captcha_text["sn"] = sn
            sn_captcha_text["captcha"] = captcha

        run_nums += 1
        return sn_captcha_text

    #测试环境按照下面的执行逻辑来执行
    elif os.environ["ENV"] == "test":
        sn = get_captcha()[0]
        sn_captcha_text["sn"] = sn
        sn_captcha_text["captcha"] = "aaaa"
        return sn_captcha_text




        # if not sn_captcha_text or run_nums % 2 == 0:
        #     sn, image = get_captcha()
        #     captcha = dddd_ocr_text(image)
        #     sn_captcha_text["sn"] = sn
        #     sn_captcha_text["captcha"] = captcha
        #
        # run_nums += 1
        # return sn_captcha_text





